<template>
    <div
        class="cancelCardReasonList"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <!-- 销卡原因明细查询 -->
        <!-- <PageTitle pageTitle="销卡原因明细查询" /> -->
        <div class="formContainer">
            <!-- 搜索表单模块 -->
            <el-form
                class="searchForm"
                ref="searchForm"
                :model="searchForm"
                :inline="true"
                label-position="right"
                size="small"
                label-width="110px"
                :rules="rules"
            >
                <el-row>
                    <el-col :span="6">
                        <el-form-item prop="closeDtStart" label="开始日期:">
                            <el-date-picker
                                v-model="searchForm.closeDtStart"
                                type="datetime"
                                placeholder="请选择开始日期"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :picker-options="startOptions"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="closeDtEnd" label="结束日期:">
                            <el-date-picker
                                v-model="searchForm.closeDtEnd"
                                type="datetime"
                                placeholder="请选择结束日期"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :picker-options="endtOptions"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="卡号:" prop="closeNo">
                            <el-input placeholder="请输入卡号" v-model="searchForm.closeNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="身份证件号码:" prop="idNo">
                            <el-input placeholder="请输入身份证件号码" v-model="searchForm.idNo"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="客户姓名:" prop="custName">
                            <el-input placeholder="请输入客户姓名" v-model="searchForm.custName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="操作选项:" prop="optflag">
                            <el-select placeholder="请选择" v-model="searchForm.optflag" clearable>
                                <el-option
                                    v-for="item in optionsList"
                                    :key="item.code"
                                    :label="item.label"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="销卡原因:" prop="closecode">
                            <el-select placeholder="请选择" v-model="searchForm.closecode" clearable>
                                <el-option
                                    v-for="item in cancelReasonList"
                                    :key="item.code"
                                    :label="item.label"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="挽留成功原因:" prop="acccode">
                            <el-select placeholder="请选择" v-model="searchForm.acccode" clearable>
                                <el-option
                                    v-for="item in detentionReasonList"
                                    :key="item.code"
                                    :label="item.label"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :style="{marginBottom: '30px'}">
                    <el-col :span="6">
                        <el-form-item label="操作员:" prop="closeBy">
                            <el-input placeholder="请输入" v-model="searchForm.closeBy"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18" :style="{textAlign: 'right'}">
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-search"
                            @click="handleSearch"
                        >查 询</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-refresh-right"
                            @click="handleReset"
                        >重 置</el-button>
                        <el-button type="primary" size="small" @click="handleExport">导 出</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 表格数据展示模块 -->
        <el-table :data="tableData" stripe border class="heard-bg">
            <el-table-column
                v-for="(item, index) in tableColumn"
                :key="index"
                :label="item.label"
                :min-width="item.minWidth"
            >
                <template slot-scope="scope">
                    <span
                        v-if="item.value === 'optflag'"
                    >{{ scope.row.optflag | getTransText(optionsList) }}</span>
                    <span
                        v-else-if="item.value === 'cancelReason'"
                        v-html="formatReason(scope.row)"
                    ></span>
                    <span
                        v-else-if="item.value === 'idType'"
                    >{{ scope.row.idType | getTransText(certificateTypeList) }}</span>
                    <span v-else>{{scope.row[item.value]}}</span>
                </template>
            </el-table-column>
        </el-table>

        <Pagination
            :hanleChangeCurrentPage="hanleChangeCurrentPage"
            :handleChangeSize="handleChangeSize"
            :total="total"
            :pageSize="pageSize"
            :currentPage="currentPage"
        />
    </div>
</template>

<script>
import moment from 'moment';
import Pagination from '@/components/Pagination/Pagination.vue';
import { getDictSelectList, isNull } from '@/utils/Common';
import request from '@/apis/request';
import { eachProp } from '@/utils/Object';

import PageTitle from '@/components/pageTitle/PageTitle.vue';
import { getToken, getTokenHsbankNo } from '@/utils/auth';

export default {
    name: 'cancelCardReasonList',
    components: {
        Pagination,
        PageTitle,
    },
    data() {
        return {
            currentPage: 1, // 当前分页
            pageSize: 10, // 每页数量
            total: 0, // 数据总数
            pageLoading: false, // 查询按钮loading
            searchForm: { // 搜索表单字段
                closeDtStart: '', // 开始日期
                closeDtEnd: '', // 截止日期
                optflag: '', // 操作选项
                closecode: '', // 销卡原因
                acccode: '', // 挽留成功原因
                closeBy: '', // 操作员号
                closeNo: '', // 卡号
                custName: '', // 客户姓名
                idNo: '', // 身份证件号码
            },
            certificateTypeList: [], // 证件类型
            cancelReasonList: [], // 销卡原因选择列表
            detentionReasonList: [], // 挽留成功原因选择列表
            optionsList: [], // 操作选项选择列表
            timeAreaList: [], // 时间区段选择列表
            // 表格展示项
            tableColumn: [
                {
                    label: '操作员',
                    value: 'closeBy',
                    minWidth: '5%',
                },
                {
                    label: '销卡日期',
                    value: 'closeDt',
                    minWidth: '10%',
                },
                {
                    label: '来电号码',
                    value: 'cardNo',
                    minWidth: '10%',
                },
                {
                    label: '卡号',
                    value: 'closeNo',
                    minWidth: '10%',
                },
                {
                    label: '客户姓名',
                    value: 'custName',
                    minWidth: '12%',
                },
                {
                    label: '证件类型',
                    value: 'idType',
                    minWidth: '8%',
                },
                {
                    label: '证件号码',
                    value: 'idNo',
                    minWidth: '10%',
                },
                {
                    label: '操作',
                    value: 'optflag',
                    minWidth: '7%',
                },
                {
                    label: '销卡原因 / 挽留成功原因',
                    value: 'cancelReason',
                    minWidth: '28%',
                },
            ],
            // 表格数据
            tableData: [],
            rules: {
                closeDtStart: [
                    { required: true, message: '请选择起始日期', trigger: 'blur' },
                ],
                closeDtEnd: [
                    { required: true, message: '请选择截止日期', trigger: 'blur' },
                ],
            },
            // 开始日期选择 限制
            startOptions: {
                disabledDate: (time) => {
                    if (this.searchForm.closeDtEnd) {
                        return time.getTime() > new Date(moment(this.searchForm.closeDtEnd).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },

            // 结束日期选择限制
            endtOptions: {
                disabledDate: (time) => {
                    if (this.searchForm.closeDtStart) {
                        return time.getTime() < new Date(moment(this.searchForm.closeDtStart).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
        };
    },
    created() { },
    mounted() {
        // 初始化方法
        this.init();
    },

    filters: {
        // 转译
        getTransText(val, list) {
            let text = '';
            if (val !== undefined) {
                list.forEach((item) => {
                    if (item.code === val) {
                        text = item.label;
                    }
                });
            }
            return text;
        },


    },
    methods: {
        async init() {
            // 证件类型选择列表
            this.certificateTypeList = await getDictSelectList('IDTYPE', this);

            // 销卡原因选择列表
            this.cancelReasonList = await getDictSelectList('CLOSECODE', this);
            this.cancelReasonList.unshift({
                code: '',
                label: '全部',
            });
            // 挽留成功原因选择列表
            this.detentionReasonList = await getDictSelectList('ACCCODE', this);
            this.detentionReasonList.unshift({
                code: '',
                label: '全部',
            });
            // 操作选项选择列表
            this.optionsList = await getDictSelectList('OPTFLAG', this);
            this.optionsList.unshift({
                code: '',
                label: '全部',
            });
            // 时间区段选择列表
            // this.timeAreaList = await getDictSelectList('INTERVAL', this)
            // this.timeAreaList.push({
            //     code: '',
            //     label: '全部'
            // })
            // 默认查询
            // this.getListData()
        },

        // 获取表格数据
        getListData() {
            this.$refs.searchForm.validate((valid) => {
                if (valid) {
                    this.pageLoading = true;
                    const params = {
                        ...this.searchForm,
                        bankNum: getTokenHsbankNo('HsbankNo'), // 银行号
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                    };

                    // 查询接口
                    this.$post.businessStatistics.getCancelCardList(params).then((res) => {
                        this.pageLoading = false;
                        if (res.status == 200 && res.data.success) {
                            this.tableData = res.data.content.page.records || [];
                            this.total = res.data.content.page.total;
                            if (this.tableData.length) {
                                this.$message.success('查询成功');
                            } else {
                                this.$alert(res.data.msg, '提示', {
                                    customClass: 'warning', type: 'warning',
                                });
                            }
                        } else {
                            this.$alert('查询失败', '提示', {
                                customClass: 'error', type: 'error',
                            });
                        }
                    });
                } else {

                }
            });
        },

        // 点击导出 -> 导出流水记录表格
        handleExport() {
            this.$refs.searchForm.validate((valid) => {
                if (!valid) return;
                const data = {
                    ...this.searchForm,
                    bankNum: getTokenHsbankNo('HsbankNo'), // 银行号
                };
                // console.log(data)
                let url = '/iccsrv/tbCloseCard/download?';
                eachProp(data, (prop) => {
                    if (!isNull(data[prop])) {
                        url += `${prop}=${data[prop].toString()}&`;
                    }
                });
                url = url.substring(0, url.length - 1);
                request({
                    url,
                    method: 'get',
                    responseType: 'blob',
                }).then((res) => {
                    // console.log(res, '相应报文')
                    const blobUrl = window.URL.createObjectURL(new Blob([res.data]));
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.download = `cancelCard_${new Date().getTime()}.xls`;
                    a.href = blobUrl;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                });
            });
        },

        // 点击查询
        handleSearch() {
            this.currentPage = 1;
            this.getListData();
        },

        // 点击重置搜索表单
        handleReset() {
            this.$refs.searchForm.resetFields();
            this.tableData = [];
            this.currentPage = 1;
            // this.getListData()
        },

        // 销卡原因 格式处理
        formatReason(rowData) {
            let val;
            if (rowData.optflag === '0' || rowData.optflag === '2') { // 显示挽留成功原因
                val = rowData.acdesc;
            } else {
                val = rowData.ccdesc;
            }
            let text = '<ul>';
            // if (!val.trim()) return text
            const arr = val.split('<br>');
            arr.forEach((item, index) => {
                if (item) {
                    if (index === arr.length - 1) {
                        text += `<li class='tableItem'>${index + 1}.${item}</li>`;
                    } else {
                        text += `<li class='tableItem'>${index + 1}.${item}</li>`;
                    }
                }
            });
            text += '</ul>';
            return text;
        },

        // 切换分页大小
        handleChangeSize(val) {
            this.pageSize = val;
            // 重置页码
            this.currentPage = 1;
            this.getListData();
        },

        // 切换页码
        hanleChangeCurrentPage(val) {
            this.currentPage = val;
            this.getListData();
        },
    },
};
</script>
<style lang="scss">
.cancelCardReasonList {
    .searchForm {
        .el-select,
        .el-date-editor {
            width: 100%;
            /* max-width: 200px; */
        }
    }
    .tableItem {
        text-align: left !important;
    }
}
</style>
<style lang="scss" scoped>
.cancelCardReasonList {
    padding: 20px;
    background-color: #fff;

    .formContainer .el-input__inner {
        width: 100%;
        /* max-width: 200px; */
    }
}
</style>
